<?php
// 应用公共文件

use think\api\Client;
use think\captcha\facade\Captcha;
use think\facade\Cache;
use think\facade\Env;

/**
 * 多维数组合并
 * @param $array1
 * @param $array2
 * @return array
 */
function array_merge_multiple($array1, $array2)
{
    $merge = $array1 + $array2;
    $data = [];
    foreach ($merge as $key => $val) {
        if (
            isset($array1[$key])
            && is_array($array1[$key])
            && isset($array2[$key])
            && is_array($array2[$key])
        ) {
            $data[$key] = array_merge_multiple($array1[$key], $array2[$key]);
        } else {
            $data[$key] = isset($array2[$key]) ? $array2[$key] : $array1[$key];
        }
    }
    return $data;
}

/**
 * 获取图片验证码参数
 * @return string
 */
function getVerifyKey():string
{
    $generator = Captcha::generate();
    Cache::tag('cache')->set('captcha_'.$generator['key'],$generator,300);
    return $generator['key'];
}

/**
 * 返回渲染好的图片验证码
 * @return object
 */
function setVerify():object
{
   return Captcha::create('verify',Cache::get('captcha_'.request()->param('key')));
}

/**
 * 校验验证码
 * @return bool
 * @param String $VerifyCode 
 * @param String $key
 */
function  checkVerify(String $VerifyCode,String $key):bool
{
    // 判断验证码是否存在
    if(empty(Cache::get('captcha_'.$key))  ||  strtolower($VerifyCode) != strtolower(Cache::get('captcha_'.$key)['value']))
    {
        return false;
    }
    Cache::delete('captcha_'.$key);
    return true;
}

/**
 * 获取城市
 * @param String $ip
 * @return String
 */
function  getCity(String $ip = ""):String
{
   // 获取客户端IP(本地调试获取到的是127.0.0.1)
   if(empty($ip))
   {
    $ip =  request()->ip() != '127.0.0.1'? request()->ip():'219.131.10.221';
   }
   // 根据IP获取城市(需要配置根目录下.env 参数)
   $city = json_decode(file_get_contents("https://apis.map.qq.com/ws/location/v1/ip?ip=".$ip."&key=".Env::get('client.client_key').""),true);
   if(isset($city['result']['ad_info']['city']))
   {
    return $city['result']['ad_info']['city'];
   }
   return '';
}


/**
 * 获取城市天气
 * @return array
 */
function  getWeather():array
{
    // 判断是否存在缓存(减少API接口请求:因为免费只有100次.寻思100个城市够了.)
    $city = getCity();
    if(!$Weather = Cache::get($city))
    {
        // 实例化ThinkApi客户端 
        $client = new Client(Env::get('client.client_code'));
        // 获取天气预报
        $Weather = $client->WeatherQuery()
            ->withCity(mb_substr($city,0,mb_strlen($city,'UTF-8')-1,'UTF-8')?:"惠州")
            ->request();
        // 设置过期时间为今天最后一秒
        $t = time();
        // 存入缓存
        Cache::tag('cache')->set($city,$Weather,bcsub(mktime(23,59,59,date("m",$t),date("d",$t),date("Y",$t)),$t));
    }
    return $Weather;
}